<template>
    <div id="ConversationList">
      <div class="content-left">
        <!-- 搜索框 -->
        <div class="search"><search/></div>
        <!-- 会话列表 -->
        <el-scrollbar v-if="conversationList.length > 0 " style="height: 95%">
          <div style="height: 520px">
            <conversation v-for="item in conversationList"
                           @scrollbarBottom="scrollbarBottom"
                          :conversation="item"
                          :key="item.id"/>
          </div>
        </el-scrollbar>
      </div>
      <!-- 会话内容展示 -->
      <div v-if="toUser" class="content-right">
        <!-- 头部 -->
        <div class="headline"> <h3>{{toUser.username}}</h3>  </div>
        <!-- 主要 -->
        <div v-if="conversationMessage" class="main">
          <el-scrollbar :key="currentConversation.id" ref="myScrollbar" style="height: 100%">
            <div style="height: 520px">
              <template v-if="isLoad">
                <el-button @click="loadMessage" ref="load" class="load"
                           :loading="loading" type="primary">
                  加载更多
                </el-button>
              </template>
              <template v-else><div class="unload">没有更多了</div></template>
              <conversation-message
                                    v-for="item in conversationMessage.messages"
                                    :message="item"
                                    :key="item.id" />
            </div>
          </el-scrollbar>
        </div>
        <!-- 底部 -->
        <div :style="bgColor" class="bottom">
          <!-- 功能按钮 -->
          <div class="function-btn">
            <ul class="left">
              <!-- 表情 -->
              <li>
                <el-popover placement="top" width="440"
                            v-model="emojiSelectVisible"
                            :offset="-180"
                            trigger="manual">
                    <el-tooltip  :open-delay="700"
                                 v-for="(item,index) in EMOJI"
                                 effect="dark"
                                 placement="top"
                                 :content="item.name">
                      <span @click="getClickEmoji(index)"
                            class="emoji"
                            :key="index">{{item.emoji}}</span>
                    </el-tooltip>
                  <svg-icon @focus="emojiSelectVisible=true"
                            @blur="emojiSelectVisible=false"
                            slot="reference" icon-class="function01"/>
                </el-popover>
              </li>
              <!-- 上传图片 -->
              <li>
<!--                <el-upload name="part" :action="action+'/upload/image'"-->
<!--                           :on-progress=""-->
<!--                           :on-change=""-->
<!--                           :on-success=""-->
<!--                           :before-upload=""-->
<!--                           accept=""-->
<!--                           :multiple="false">-->
                  <svg-icon icon-class="function02"/>
<!--                </el-upload>-->
              </li>
              <!-- 上传视频 -->
              <li>
                <el-upload name="part" :action="action+'/upload/video'" :multiple="false"
                           :on-success="videoUploadSuccess"
                           :before-upload="beforeUploadVideo"
                           :on-change="sendVideo"
                           :on-progress="videoUploadProgress"
                           accept=".mp4"
                           :show-file-list="false">
                  <svg-icon icon-class="function03"/>
                </el-upload>
              </li>
              <li>
                <svg-icon icon-class="function04"/>
              </li>
            </ul>
            <ul class="right">
              <li>
                <svg-icon icon-class="function05"/>
              </li>
              <li>
                <svg-icon icon-class="function06"/>
              </li>
            </ul>
          </div>
          <!-- 文本输入框 -->
          <div class="text-box">
            <textarea @focus="bgColor={backgroundColor: '#ffffff'}"
                      @blur="bgColor=''"
                      @keyup.ctrl.enter="sendTextMessage"
                      :style="bgColor"
                      v-model="content"
                      rows="6"/>
          </div>
          <el-tooltip class="item" effect="dark" content="按Ctrl+Enter发送消息" placement="left">
            <div @click="sendTextMessage"
                 class="send"><i class="el-icon-s-promotion"/></div>
          </el-tooltip>
        </div>
      </div>
    </div>
</template>

<script>
  import Search from "@/views/chat/Search";
  import Conversation from "@/views/chat/Conversation";
  import ConversationMessage from "@/views/chat/ConversationMessage";
  import {mapGetters} from 'vuex'
  import EMOJI from "@/utils/emoji";
  import {sendConversationMessage,getConversationListMessage} from "@/api/conversation";
  import {sendMessage} from "@/websocker";
  import messageType from "@/utils/message-type";

  export default {
        name: "ConversationList",
      components:{
          Search,Conversation,ConversationMessage
      },
      data(){
          return{
            EMOJI, // emoji 表情库
            emojiSelectVisible:false,//表情选择面板
            content:'', //消息内容
            bgColor:'',
            loading:false,
            action:process.env.VUE_APP_BASE_API,
            message:{},
          }
      },
      computed:{
        ...mapGetters([
          'id','friendList','conversationList','currentConversation','conversationMessagesList'
        ]),
        // 聊天对象信息
        toUser(){
          let {fromId, toId} = this.currentConversation;
          let id = fromId === this.id ? toId : fromId;
          return this.friendList.filter(item=>item.userid === id)[0]
        },
        // 会话信息
        conversationMessage(){
          let result = this.conversationMessagesList.filter(item => {
           return  item.conversationId === this.currentConversation.id
          })[0];
          console.log(result)
          return result
        },
        // 是否显示加载聊天记录按钮
        isLoad(){
          if(this.conversationMessage){
            console.log(this.conversationMessage)
            let total = this.conversationMessage.totalPages;
            let page = this.conversationMessage.page;
            return  total?false:(total-page>0)
          }
          return false;
        }
      },
      watch:{
        'conversationMessage.messages' :function (newMessages,oldMessages) {
          this.$nextTick(()=>{
            if(this.$refs['myScrollbar']){
              let scrollbar = this.$refs['myScrollbar'].wrap;
              scrollbar.scrollTop = scrollbar.scrollHeight
            }
            // if(!oldMessages){
            //   console.log(oldMessages)
            //   scrollbar.scrollTop = scrollbar.scrollHeight
            // }else {
            //   console.log(oldMessages)
            //   if(oldMessages.length === 0 || newMessages.length === 0){
            //
            //   }
            //   if(oldMessages[0].conversationId === newMessages[0].conversationId){
            //   }else if(this.conversationMessage.scrollTop){
            //     scrollbar.scrollTop = this.conversationMessage.scrollTop
            //   }
            // }
            //
            // if(this.conversationMessage.scrollTop){
            //   scrollbar.scrollTop = this.conversationMessage.scrollTop
            // }
            // if(this.$refs['myScrollbar'].wrap.onscroll){
            //   return
            // }
            // this.$refs['myScrollbar'].wrap.onscroll=()=>{
            //   this.$set(this.conversationMessage,'scrollTop',scrollbar.scrollTop)
            // }
          })
        },
      },
      methods:{
          // 将用户点击的表情追加到文本框中
        getClickEmoji(index) {
          this.content += this.EMOJI[index].emoji
          console.log(this.EMOJI[index])
        },
        scrollbarBottom(){
          this.$nextTick(()=>{
            this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
          })
        },
        // 发送文本消息
        sendTextMessage(){
          if (this.content.trim()==='') {
            this.$message.info("消息内容不能为空！")
          }else{
            this.message = this.initialMessage(this.content,1);
            this.sendMessage();
            this.conversationMessage.messages.push(this.message);// 将消息保存到会话列表
            this.content = ''
          }
        },
        // 发送消息
        sendMessage() {
          // 将消息发送到服务器进行保存
          sendConversationMessage(this.message).then(res => {
            let {message} = res.content
            // 更新最后一条消息
            this.$set(this.currentConversation, 'lastMessage', message);
            message.form = messageType.CONVERSATION_MESSAGE // 设置消息形式为聊天
            sendMessage(message);// 使用webSocket将消息发送给接收者
          });
        },
        // 加载消息
        async loadMessage(){
          this.loading = true;
          let page = this.conversationMessage.page+1
          // 获取当前滚动条的高度
          let oldScrollHeight= this.$refs['myScrollbar'].wrap.scrollHeight
          console.log(oldScrollHeight)
          await getConversationListMessage(this.currentConversation.id,page).then(res=>{
            res.content.messages.reverse()
            console.log(...res.content.messages)
            this.conversationMessage.messages.unshift(...res.content.messages);
            this.$set(this.conversationMessage,'page',page)
            console.log(this.conversationMessage.messages)
            this.loading = false
          })
          // 获取数据更新后的滚动条
          let newScrollHeight = this.$refs['myScrollbar'].wrap.scrollHeight;
          console.log(newScrollHeight)
          this.$nextTick(()=>{
            // 定位滚条回到之前的位置
            this.$refs['myScrollbar'].wrap.scrollTop = newScrollHeight-oldScrollHeight
          })
        },
        // 视频上传成功后的回调函数
        videoUploadSuccess(res){
          console.log(res)
          // 视频进度条隐藏
          this.$set(this.message, 'showProgress', false);
          this.$set(this.message,'content',res.content.video)
          this.sendMessage() // 发送消息到服务器以及接收方
        },
        // 视频上传之前的回调函数，用于限制视频上传大小和格式
        beforeUploadVideo(file){
          const isLt1024M = file.size / 1024 / 1024 > 1024;
          if(['video/mp4'].indexOf(file.type) === -1){
            this.$message.error("请上传正确的视频格式！")
            return false
          }
          if(isLt1024M){
            this.$message.error("上传视频大小不能超过1024MB哦！")
            return false
          }
          return true
        },
        // 视频消息上传进度
        videoUploadProgress(event){
          this.$set(this.message,'loaded',event.loaded);
          console.log(event.loaded+'======>'+event.total)
        },
        //发送视频消息
        sendVideo(file){
          // 判断文件的状态
          if (file.status === 'ready') {
            // 获取本地图片地址
            let localFileUrl = URL.createObjectURL(file.raw);
            // 初始化要发送的消息
            this.message = this.initialMessage(localFileUrl,3)
            this.$set(this.message,'showProgress',true) //设置 消息的进度条为显式
            this.$set(this.message,'total',file.size) // 设置 消息中包含文件的总大小
            this.$set(this.message,'loaded',0) // 设置 消息中文件上传的进度
            this.conversationMessage.messages.push(this.message);// 将消息保存到会话列表
          }
        },
        // 初始化消息
        initialMessage(content,type){
          return {
            fromId:this.id, // 消息发送者id
            toId: this.toUser.userid, // 消息接收id
            sendTime: new Date().getTime(), // 消息发送时间
            status: false, // 消息状态
            conversationId: this.currentConversation.id, // 消息所属会话id
            content:content, // 消息内容，
            type:type // 消息类型  1：文本消息 2：图片消息 3：视频消息
          }
        },
      },
  }
</script>

<style>
  /* 隐藏el-scrollbar底部滚动条  */
  #ConversationList .el-scrollbar__wrap{overflow-x:hidden;}
</style>

<style scoped>
  .emoji{
    padding: 3px;
    font-size: 17px;
  }
  .emoji:hover{
    cursor: pointer;
    border: 1px solid #cdcdcd;
  }
</style>
<style lang="scss" scoped>
  #ConversationList {
    display: flex;
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    /* 隐藏el-scrollbar底部滚动条  */
    .el-scrollbar__wrap{overflow-x:hidden;}
    .content-left{
      width: 28%;
      max-width: 300px;
      height: 100%;
      border-top: 1px solid transparent;
      border-right: 1px solid #eae8e8;
      background-color: #f6f6f6;
    }
    .search {
      margin: 14px 12px 20px;
    }
    .content-right{
      flex: 2;
      display: flex;
      flex-direction: column;
      border-left: 1px solid #e5e5e5;
      .headline{
        flex: 0.25;
        height: 40px;
        border-bottom: 1px solid #e5e5e5;
        h3{
          font-size: 20px;
          font-weight: 400;
          margin-left: 28px;
          line-height: 40px;
        }
      }
      .main {
        flex: 2.8;
        height: 100%;
        border-bottom: 1px solid #e5e5e5;
        text-align: center;
        .unload {
          margin-top: 8px;
          color: #a5b5c1;
          font-size: 12px;
        }
        .load {
          background-color: #f5f5f5;
          color: #20a0ff;
          border: 0;
          width:60px;
          height: 20px;
          padding: 8px 0 0;
          font-size: 12px;
        }
      }
      .bottom {
        flex: 0.6;
        position: relative;
        height: 100%;
        padding: 5px 20px 20px 20px;
        .function-btn {
          height: 30px;

          ul {
            padding: 0;
            margin: 0 0;
            list-style: none;

            li {
              cursor: pointer;
              font-size: 18px;
              color: #919191;
              margin-right: 12px;
              display: inline-block;
            }
          }

          .left {
            float: left;
          }

          .right {
            float: right;
          }
        }

        .text-box {
          height: 16%;

          textarea {
            background-color: #f5f5f5;
            width: 100%;
            outline: none;
            font-size: 14px;
            border: none;
            resize: none;
          }
        }
        .send {
          position: absolute;
          right: 20px;
          bottom: 22px;
          width: 32px;
          height: 25px;
          font-size: 25px;
          text-align: center;
          cursor: pointer;

          &:hover {
            color: #20a0ff;
          }
        }
      }
    }
  }
</style>
